package com.lyn.pluginhost.activity

import android.annotation.SuppressLint
import android.util.Log
import java.util.Stack

/**
 *
 * @author longyn 2025/07/10
 * @version 1.0.0
 */
internal class ProxyPluginActivityStack {

    companion object {
        const val TAG = "ProxyPluginActivityStack"
        val instance by lazy { ProxyPluginActivityStack() }
    }

    private val activityStack: Stack<ProxyPluginActivity> = Stack()

    fun push(activity: ProxyPluginActivity) {
        activityStack.push(activity)
    }

    fun peek(): ProxyPluginActivity? {
        if (activityStack.isEmpty()) {
            return null
        }
        return activityStack.peek()
    }

    fun pop(): ProxyPluginActivity? {
        if (activityStack.isEmpty()) {
            return null
        }
        return activityStack.pop()
    }

    @SuppressLint("LongLogTag")
    fun remove(activity: ProxyPluginActivity){
        if (activityStack.isEmpty()) {
            return
        }
        for (act in activityStack){
            if (act == activity){
                activityStack.remove(activity)
                Log.d(TAG,"remove activity${act.pluginId}")
            }
        }
    }

    @SuppressLint("LongLogTag")
    fun close(id: String) {
        if (activityStack.isEmpty()) {
            return
        }
        for (activity in activityStack) {
            if (activity.pluginId == id) {
                activity.finish()
                Log.d(TAG,"close:${activity::class.java.name}")
            }
        }
    }

    fun closeAll(){
        if (activityStack.isEmpty()){
            return
        }
        for (activity in activityStack) {
            activity.finish()
        }
    }

    fun getActivityStack(): Stack<ProxyPluginActivity> {
        return activityStack
    }
}